package cn.com.checne.controller.superManager.synch;

import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.com.checne.constants.SynchConstants;
import cn.com.checne.dao.ContentInfoDao;
import cn.com.checne.dao.LanguageInfoDao;
import cn.com.checne.dao.MsgInfoDao;
import cn.com.checne.dao.NewsInfoDao;
import cn.com.checne.dao.UserInfoDao;
import cn.com.checne.dao.WebsiteInfoDao;
import cn.com.checne.model.domain.ContentInfo;
import cn.com.checne.model.domain.MsgInfo;
import cn.com.checne.model.domain.WebsiteInfo;
import cn.com.checne.util.BlowFish;
import cn.com.checne.util.HttpConnection;
import cn.com.checne.util.WebUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Controller
public class ContentInfoSynchController {
	protected static final Logger logger = Logger
			.getLogger(ContentInfoSynchController.class);
	private static final BlowFish bf = new BlowFish(SynchConstants.SYNCH_SECRET_KEY);
	private static final Gson gson = new Gson();

	@Resource
	private ContentInfoDao contentDao;

	@Resource
	private WebsiteInfoDao websiteInfoDao;

	@Resource
	private UserInfoDao userInfoDao;

	@Resource
	private MsgInfoDao msgInfoDao;

	@Resource
	private LanguageInfoDao languageInfoDao;

	/*@Resource
	private ChannelInfoDao channelInfoDao;*/

	@Resource
	private NewsInfoDao newsInfoDao;

	@RequestMapping(value = SynchConstants.SYNCH_CONTENT_SEND, method =RequestMethod.GET)
	public ModelAndView contentSend(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		StringBuilder message = new StringBuilder();
		ModelAndView mav = new ModelAndView("common/message");
		String strContentIds = request.getParameter("contentId");
		String strWebsiteIds = request.getParameter("websiteId");
		if ((StringUtils.isBlank(strContentIds))|| (StringUtils.isBlank(strWebsiteIds))) {
			map.put("message", "请选择要同步的地址!");
			mav.addAllObjects(map);
			mav.setViewName("common/message");
			return mav;
		}

		String[] contentIds = StringUtils.split(strContentIds, ",");
		String[] websiteIds = StringUtils.split(strWebsiteIds, ",");

		List<WebsiteInfo> websiteInfoList = new ArrayList<WebsiteInfo>();
		for (String websiteId : websiteIds) {
			websiteInfoList.add(websiteInfoDao.getWebsite(Integer.valueOf(websiteId).intValue()));
		}
		List<ContentInfo> contentInfoList = new ArrayList<ContentInfo>();
		for (String contentId : contentIds) {
			contentInfoList.add(contentDao.getContentById(contentId));
		}

		for (WebsiteInfo website : websiteInfoList) {
			int msgFrom = websiteInfoDao.getWebsiteSelf().getId();
			int msgTo = website.getId();
			String contentInfoString = gson.toJson(contentInfoList, List.class);
			String synchURL = website.getUrl() + SynchConstants.SYNCH_CONTENT_REV;
			StringBuilder synchContent = new StringBuilder();
			synchContent.append("sign=" + bf.encryptString(contentInfoString));
			synchContent.append("&from=" + bf.encryptString(String.valueOf(msgFrom)));
			synchContent.append("&to=" + bf.encryptString(String.valueOf(msgTo)));
			logger.info("[synch-contentInfo] [" + synchURL + "] " + synchContent);

			String result = HttpConnection.sendPost(synchURL, synchContent.toString());

			if (StringUtils.isNotBlank(result)) {
				if (StringUtils.equals(result,SynchConstants.SYNCH_RESULT_OK)) {
					message.append(website.getName() + "&nbsp;&nbsp;同步" + "成功!\r\n");
					for (ContentInfo content : contentInfoList) {
						MsgInfo msgInfo = new MsgInfo();
						msgInfo.setMsgFrom(msgFrom);
						msgInfo.setMsgTo(msgTo);
						msgInfo.setContentId(content.getContentId());
						msgInfo.setMsgStatus(1);
						msgInfoDao.synchMsg(msgInfo);
					}
				} else if (StringUtils.equals(result,SynchConstants.SYNCH_RESULT_NOPWD)) {
					message.append(website.getName() + "&nbsp;&nbsp;密钥验证失败!\r\n");
				} else {
					message.append(website.getName() + "&nbsp;&nbsp;同步" + "失败!\r\n");
				}
			}
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping(value = SynchConstants.SYNCH_CONTENT_REV, method =RequestMethod.POST)
	public void contentRev(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		PrintWriter out = response.getWriter();
		String sign = WebUtils.getRequestParameterAsString(request, "sign");
		String from = WebUtils.getRequestParameterAsString(request, "from");
		String to = WebUtils.getRequestParameterAsString(request, "to");

		if ((StringUtils.isBlank(sign)) || (StringUtils.isBlank(from)) || (StringUtils.isBlank(to))) {
			out.print(SynchConstants.SYNCH_RESULT_NOPWD);
			out.close();
			return;
		}
		sign = bf.decryptString(sign);
		from = bf.decryptString(from);
		to = bf.decryptString(to);

		Type type = new TypeToken<List<ContentInfo>>() {}.getType();
		List<ContentInfo> list = gson.fromJson(sign, type);
		try {
			for (ContentInfo content : list) {
				contentDao.insert(content);
				MsgInfo msgInfo = new MsgInfo();
				msgInfo.setMsgFrom(Integer.valueOf(from).intValue());
				msgInfo.setMsgTo(Integer.valueOf(to).intValue());
				msgInfo.setContentId(content.getContentId());
				msgInfo.setMsgStatus(2);
				msgInfoDao.synchMsg(msgInfo);
			}
			out.print(SynchConstants.SYNCH_RESULT_OK);
		} catch (Exception e) {
			logger.error("[synch-contentInfo] rev error ", e);
			out.print("0");
		}
	}

	/*@SuppressWarnings("unchecked")
	@RequestMapping(value = { "/synch/contentInfo/contentReadSend.do" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public ModelAndView contentEditForUse(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/newsInfo/newsInfoEdit");

		String contentId = WebUtils.getRequestParameterAsString(request,
				"contentId");
		int websiteId = WebUtils.getRequestParameterAsInt(request, "websiteId",
				0);
		ContentInfo contentInfo = contentDao.getContentById(contentId);
		WebsiteInfo websiteInfo = websiteInfoDao.getWebsite(websiteId);

		int languageId = 1;
		String title = contentInfo.getTitle();
		String tag = "";
		String author = ((UserInfo) session.getAttribute("systemUserInfo"))
				.getRealName();
		int userId = ((UserInfo) session.getAttribute("systemUserInfo"))
				.getId();
		String from = "";
		String publishTime = contentInfo.getPublishTime();
		int isFouceImage = 0;
		String keywords = "";
		String newsMeta = "";

		int isShowInIndex = 0;
		int isShowInList = 0;
		int isTop = 0;
		int isReview = 0;

		int textType = 1;
		String content = contentInfo.getText();

		NewsInfo newsInfo = new NewsInfo();
		newsInfo.setLanguageId(languageId);
		newsInfo.setTitle(title);
		newsInfo.setTag(tag);
		newsInfo.setAuthor(author);
		newsInfo.setUserId(userId);
		newsInfo.setFrom(from);
		newsInfo.setPublishTime(publishTime);
		newsInfo.setIsFouceImage(isFouceImage);
		newsInfo.setMainImage("");
		newsInfo.setKeywords(keywords);
		newsInfo.setNewsMeta(newsMeta);
		newsInfo.setTextType(textType);
		newsInfo.setContent(content);
		newsInfo.setChannelIds("");

		NewsChannelRel rel = new NewsChannelRel();
		rel.setIsShowInIndex(isShowInIndex);
		rel.setIsShowInList(isShowInList);
		rel.setIsReview(isReview);
		rel.setIsTop(isTop);

		NewsDTO newsDTO = new NewsDTO();
		newsDTO.setNewsInfo(newsInfo);
		newsDTO.setRel(rel);
		newsInfoDao.insert(newsDTO);

		List<LanguageInfo> languageInfoList = languageInfoDao.getAll();
		List<ChannelInfo> channelInfoList = channelInfoDao.getALL();
		map.put("channelIds", "");
		map.put("channelNames", "");
		map.put("tagWordsId", "");
		map.put("tagWords", "");
		map.put("newsDTO", newsDTO);
		map.put("languageInfoList", languageInfoList);
		map.put("channelInfoList", channelInfoList);
		map.put("userRightsSession",
				(List<String>) session.getAttribute("systemUserRigthList"));
		map.put("userInfoSession",
				(UserInfo) session.getAttribute("systemUserInfo"));
		map.put("languageId", Integer.valueOf(languageId));
		map.put("newsId", Integer.valueOf(newsDTO.getNewsInfo().getNewsId()));
		map.put("relId", Integer.valueOf(newsDTO.getRel().getId()));
		map.put("act", "update");
		map.putAll(environment);
		List<UserInfo> userInfoList = userInfoDao.getUserListByRoleId(-1, 0,
				2147483647);
		map.put("userInfoList", userInfoList);
		map.put("userInfoList", userInfoList);

		map.put("synchType", "Y");
		map.put("contentId", contentId);
		map.put("websiteId", Integer.valueOf(websiteId));
		mav.addAllObjects(map);

		if (websiteInfo.getIsSelf() != 1) {
			msgInfoDao.isAlwaysRead(websiteId, contentId);

			String synchURL = null;
			StringBuilder synchContent = new StringBuilder();
			String result = null;
			try {
				synchURL = websiteInfo.getUrl()
						+ "/synch/contentInfo/contentReadRev.do";
				synchContent.append("sign="
						+ bf.encryptString("c05f2c0f21f749519a55e621c1a16d77"));
				synchContent.append("&websiteId="
						+ bf.encryptString(String.valueOf(websiteId)));
				synchContent
						.append("&contentId=" + bf.encryptString(contentId));
				logger.info("[synch-contentInfo-read-send] [" + synchURL + "] "
						+ synchContent);

				result = HttpConnection.sendPost(synchURL,
						synchContent.toString());
				logger.info("[synch-contentInfo-read-send] [" + synchURL + "] "
						+ result);
			} catch (Exception e) {
				logger.info("[synch-contentInfo-read-send] [" + synchURL + "] "
						+ result);
			}
		}

		return mav;
	}

	@RequestMapping(value = { "/synch/contentInfo/contentEditForUseExit.do" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public ModelAndView contentEditForUseExit(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		int newsId = WebUtils.getRequestParameterAsInt(request, "newsId", 0);
		if (newsInfoDao.deleteNewsContentInfo(newsId)) {
			ModelAndView mav = new ModelAndView(
					"admin/contentInfo/contentInfoList");
			int curPage = WebUtils.getRequestParameterAsInt(request, "curPage",
					1);
			String kw = WebUtils.getRequestParameterAsString(request, "kw");
			int websiteId = WebUtils.getRequestParameterAsInt(request,
					"websiteId", 0);
			int userId = WebUtils
					.getRequestParameterAsInt(request, "userId", 0);
			PageBean pageBean = new PageBean();
			pageBean.setCurPage(curPage);
			ContentInfo query = new ContentInfo();
			query.setKw(kw);
			query.setWebsiteId(websiteId);
			query.setUserId(userId);
			List<ContentInfo> contentInfoList = contentDao.getSubList(query,
					pageBean.getStart(), pageBean.getRowsPerPage());
			pageBean.setMaxRowCount(contentDao.getCount(query));
			pageBean.setMaxPage();
			pageBean.setPageNoList();

			List<UserInfo> userInfoList = userInfoDao.getUserListByRoleId(-1, 0,
					2147483647);
			List<WebsiteInfo> websiteInfoList = websiteInfoDao.getSubList(null, 0,
					2147483647);
			map.put("contentInfoList", contentInfoList);
			map.put("pageBean", pageBean);
			map.put("content", query);
			map.put("userInfoList", userInfoList);
			map.put("websiteInfoList", websiteInfoList);
			mav.addAllObjects(map);
			return mav;
		}
		return null;
	}

	@RequestMapping(value = { "/synch/contentInfo/contentUsedSend.do" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public ModelAndView contentUse(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		int userId = StringUtils.isNotBlank(request.getParameter("userId")) ? Integer
				.parseInt(request.getParameter("userId")) : 0;
		int newsId = StringUtils.isNotBlank(request.getParameter("newsId")) ? Integer
				.parseInt(request.getParameter("newsId")) : 0;
		int relId = StringUtils.isNotBlank(request.getParameter("relId")) ? Integer
				.parseInt(request.getParameter("relId")) : 0;
		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		String title = request.getParameter("title");
		String tagWordsId = request.getParameter("tagWordsId");
		String channelIds = request.getParameter("channelIds");

		String from = request.getParameter("from");
		String publishTime = request.getParameter("publishTime");
		int isFouceImage = StringUtils.isNotBlank(request
				.getParameter("isFouceImage")) ? Integer.parseInt(request
				.getParameter("isFouceImage")) : 0;
		String keywords = request.getParameter("keywords");
		String newsMeta = request.getParameter("newsMeta");

		int isShowInIndex = StringUtils.isNotBlank(request
				.getParameter("isShowInIndex")) ? Integer.parseInt(request
				.getParameter("isShowInIndex")) : 0;
		int isShowInList = StringUtils.isNotBlank(request
				.getParameter("isShowInList")) ? Integer.parseInt(request
				.getParameter("isShowInList")) : 1;
		int isTop = StringUtils.isNotBlank(request.getParameter("isTop")) ? Integer
				.parseInt(request.getParameter("isTop")) : 0;
		int isReview = StringUtils.isNotBlank(request.getParameter("isReview")) ? Integer
				.parseInt(request.getParameter("isReview")) : 0;

		int textType = StringUtils.isNotBlank(request.getParameter("textType")) ? Integer
				.parseInt(request.getParameter("textType")) : 1;
		String content = StringUtils
				.isNotBlank(request.getParameter("content")) ? request
				.getParameter("content") : "";
		String simpleText = StringUtils.isNotBlank(request
				.getParameter("simpleText")) ? request
				.getParameter("simpleText") : "";

		if (textType == 2) {
			content = simpleText;
		}

		String mainImage = "";
		String srcRegex = "src\\s*=\\s*[\"|'](.+?[jpg|gif|png|bmp])[\"|']";
		List<String> allImages = RegexUtils.getStringGoup1(content, srcRegex);
		String appPath = request.getContextPath();
		String appURL = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort();
		String contentResult = content;
		for (String image : allImages) {
			if (!image.toLowerCase().startsWith("http")) {
				if ((StringUtils.isNotBlank(appPath))
						&& (appPath.length() == 1)) {
					mainImage = image.substring(1);
					contentResult = content.replace(image, appURL + image);
				} else {
					mainImage = image.substring(appPath.length() + 1);
					contentResult = content.replace(image, appURL + image);
				}
			} else {
				mainImage = image;
			}
		}
		NewsDTO newsDTO = new NewsDTO();
		NewsInfo updateInfo = newsInfoDao.getNewsInfoByNewsId(newsId);
		updateInfo.setNewsId(newsId);
		updateInfo.setLanguageId(languageId);
		updateInfo.setTitle(title);
		updateInfo.setTag(tagWordsId);

		if (userId > 0) {
			UserInfo userInfoSelect = userInfoDao.getUser(userId);
			updateInfo.setAuthor(userInfoSelect.getRealName());
			updateInfo.setUserId(userId);
		}
		updateInfo.setFrom(from);
		updateInfo.setPublishTime(publishTime);
		updateInfo.setIsFouceImage(isFouceImage);
		updateInfo.setMainImage(mainImage);
		updateInfo.setKeywords(keywords);
		updateInfo.setNewsMeta(newsMeta);
		updateInfo.setTextType(textType);
		updateInfo.setContent(contentResult);

		updateInfo.setChannelIds(channelIds);

		NewsChannelRel rel = new NewsChannelRel();
		rel.setId(relId);
		rel.setIsShowInIndex(isShowInIndex);
		rel.setIsShowInList(isShowInList);
		rel.setIsReview(isReview);
		rel.setIsTop(isTop);
		newsDTO.setNewsInfo(updateInfo);
		newsDTO.setRel(rel);

		if (newsInfoDao.update(newsDTO))
			message = "消息已经采用!";
		else {
			message = "消息采用失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);

		String contentId = WebUtils.getRequestParameterAsString(request,
				"contentId");
		int websiteId = WebUtils.getRequestParameterAsInt(request, "websiteId",
				0);
		WebsiteInfo websiteInfo = websiteInfoDao.getWebsite(websiteId);
		if (websiteInfo.getIsSelf() != 1) {
			msgInfoDao.isAlwaysUsed(websiteId, contentId);

			String synchURL = null;
			StringBuilder synchContent = new StringBuilder();
			String result = null;
			try {
				synchURL = websiteInfo.getUrl()
						+ "/synch/contentInfo/contentUsedRev.do";
				synchContent.append("sign="
						+ bf.encryptString("c05f2c0f21f749519a55e621c1a16d77"));
				synchContent.append("&websiteId="
						+ bf.encryptString(String.valueOf(websiteId)));
				synchContent
						.append("&contentId=" + bf.encryptString(contentId));
				logger.info("[synch-contentInfo-used-send] [" + synchURL + "] "
						+ synchContent);

				result = HttpConnection.sendPost(synchURL,
						synchContent.toString());
				logger.info("[synch-contentInfo-used-send] [" + synchURL + "] "
						+ result);
			} catch (Exception e) {
				logger.info("[synch-contentInfo-used-send] [" + synchURL + "] "
						+ result);
			}
		}

		return mav;
	}*/
}